package com.itheima.reggie.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public UserService userService;

    /**
     * app 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody  User user, HttpSession session){
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        // 默认验证码 1
        session.setAttribute(user.getPhone(),"1");
        return R.success("发送成功");
        // 短信太贵先注释掉
//        SendSmsResponse res = SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", user.getPhone(), code);
//        if(res!=null && res.getCode().equals("OK")){
//            session.setAttribute(user.getPhone(),code);
//            return R.success(res.getMessage());
//        }else{
//            return R.error(res.getMessage());
//        }
    }

    /**
     * 用户登陆
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,Object> map, HttpSession session){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        Object attribute = session.getAttribute(phone);
        if(attribute!=null && attribute.equals(code)){
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
            if (user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }else{
            return R.error("验证码有误！");
        }
    }

}
